const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/user');
const { authMiddleware } = require('../middleware/auth');

const router = express.Router();

// @route   POST api/auth/register
// @desc    Register a user
// @access  Public
router.post('/register', async (req, res) => {
  try {
    const { username, email, password, full_name, phone, address } = req.body;

    // Don't log registration details to console
    
    // Validation
    if (!username || !email || !password || !full_name) {
      const missingFields = [];
      if (!username) missingFields.push('username');
      if (!email) missingFields.push('email');
      if (!password) missingFields.push('password');
      if (!full_name) missingFields.push('full_name');
      
      console.error('Registration validation failed: Missing required fields');
      return res.status(400).json({ 
        message: '注册失败: 缺少必填字段', 
        details: `缺少字段: ${missingFields.join(', ')}` 
      });
    }

    // Email format validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      console.error('Registration validation failed: Invalid email format');
      return res.status(400).json({ message: '邮箱格式无效' });
    }

    // Username validation
    if (username.length < 3 || username.length > 20) {
      console.error('Registration validation failed: Username length invalid');
      return res.status(400).json({ message: '用户名长度必须在3到20个字符之间' });
    }

    // Password validation
    if (password.length < 6) {
      console.error('Registration validation failed: Password too short');
      return res.status(400).json({ message: '密码长度不能小于6个字符' });
    }

    // Check if user already exists
    let user = await User.findByEmail(email);
    if (user) {
      console.error('Registration failed: Email already exists');
      return res.status(400).json({ message: '该邮箱已被注册' });
    }

    user = await User.findByUsername(username);
    if (user) {
      console.error('Registration failed: Username already taken');
      return res.status(400).json({ message: '用户名已被占用' });
    }

    // Create user
    const newUser = await User.create({
      username,
      email,
      password,
      full_name,
      phone,
      address
    });

    // Only log non-sensitive information after user creation
    console.log('User created successfully');

    // Create JWT Payload
    const payload = {
      user: {
        id: newUser.id,
        username: newUser.username,
        is_admin: newUser.is_admin
      }
    };

    // Sign token
    jwt.sign(
      payload,
      process.env.JWT_SECRET,
      { expiresIn: '2h' },
      (err, token) => {
        if (err) {
          console.error('Token generation error');
          throw err;
        }
        res.json({ token });
      }
    );
  } catch (err) {
    console.error('Registration error');
    res.status(500).json({ message: '服务器错误', error: err.message });
  }
});

// @route   POST api/auth/login
// @desc    Authenticate user & get token
// @access  Public
router.post('/login', async (req, res) => {
  const { username, password } = req.body;
  
  try {
    // Check for user
    const user = await User.findByUsername(username);
    if (!user) {
      return res.status(400).json({ message: 'Invalid credentials' });
    }
    
    // Check password
    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
      return res.status(400).json({ message: 'Invalid credentials' });
    }
    
    // Create JWT Payload
    const payload = {
      user: {
        id: user.id,
        username: user.username,
        is_admin: user.is_admin
      }
    };

    // Sign token
    jwt.sign(
      payload,
      process.env.JWT_SECRET,
      { expiresIn: '2h' },
      (err, token) => {
        if (err) {
          console.error('Token generation error');
          throw err;
        }
        res.json({ token });
      }
    );
  } catch (err) {
    console.error('Login error');
    res.status(500).send('Server error');
  }
});

// @route   GET api/auth/user
// @desc    Get logged in user
// @access  Private
router.get('/user', authMiddleware, async (req, res) => {
  try {
    // Don't log user ID in requests
    
    if (!req.user || !req.user.id) {
      console.error('认证中间件未提供有效的用户ID');
      return res.status(401).json({ message: '无效的用户凭证' });
    }
    
    const user = await User.findById(req.user.id);
    
    if (!user) {
      console.error('用户不存在');
      return res.status(404).json({ message: '用户不存在' });
    }
    
    // Don't log user details
    res.json(user);
  } catch (err) {
    console.error('获取用户信息错误');
    res.status(500).json({ message: '服务器错误', error: err.message });
  }
});

// @route   GET api/auth/me
// @desc    Get logged in user (alternative endpoint)
// @access  Private
router.get('/me', authMiddleware, async (req, res) => {
  try {
    // Don't log user ID in requests
    
    if (!req.user || !req.user.id) {
      console.error('认证中间件未提供有效的用户ID');
      return res.status(401).json({ message: '无效的用户凭证' });
    }
    
    const user = await User.findById(req.user.id);
    
    if (!user) {
      console.error('用户不存在');
      return res.status(404).json({ message: '用户不存在' });
    }
    
    // Don't log user details
    res.json(user);
  } catch (err) {
    console.error('获取用户信息错误');
    res.status(500).json({ message: '服务器错误', error: err.message });
  }
});

module.exports = router; 